#include "app_mqtt.h"
#include <MQTTClient.h>
#include <stdlib.h>
#include <assert.h>
#include "log/log.h"
#include "app_router.h"

static MQTTClient client;

static void app_mqtt_connectionLost(void *context, char *cause);

static int app_mqtt_messageArrived(void *context, char *topicName, int topicLen, MQTTClient_message *message);

static void app_mqtt_deliveryComplete(void *context, MQTTClient_deliveryToken dt);

int app_mqtt_init()
{
    // 1. 初始化MQTT客户端
    if (MQTTClient_create(&client, MQTT_SERVER, MQTT_CLIENT_ID, MQTTCLIENT_PERSISTENCE_NONE, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_create failed");
        return -1;
    }

    //2.设置回调函数
    if (MQTTClient_setCallbacks(client, NULL, app_mqtt_connectionLost, app_mqtt_messageArrived, app_mqtt_deliveryComplete) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_setCallbacks failed");
        MQTTClient_destroy(&client);
        return -1;
    }
    //3.连接服务器
    MQTTClient_connectOptions options = MQTTClient_connectOptions_initializer;
    options.keepAliveInterval = 20;
    options.cleansession = 1;

    int ret = MQTTClient_connect(client, &options);
    if (ret != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_connect failed,ret: %d", ret);
        MQTTClient_destroy(&client);
        return -1;
    }
    

    //4.订阅主题
    if (MQTTClient_subscribe(client, MQTT_PULL_TOPIC, MQTT_QOS) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_subscribe failed");
        MQTTClient_disconnect(client, 10);
        MQTTClient_destroy(&client);
        return -1;
    }
    log_info("MQTT init success");
    return 0;
    
}

int app_mqtt_publish(char *mqtt_message, size_t mqtt_message_len)
{
    int ret = MQTTClient_publish(client, MQTT_PUSH_TOPIC, mqtt_message_len, mqtt_message, MQTT_QOS, false, NULL);
    if (ret != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_publishMessage failed,ret=%d", ret);
        return -1;
    }
    log_debug("MQTT publish success,content= %s", mqtt_message);
    return 0;
    
}

void app_mqtt_deinit()
{
    if (MQTTClient_disconnect(client, 10) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_disconnect failed");
    }
    MQTTClient_destroy(&client);
}

static void app_mqtt_connectionLost(void *context, char *cause)
{
    assert(context == NULL);
    log_error("MQTT connection lost,cause=%s", cause);
    exit(EXIT_FAILURE);
}

static int app_mqtt_messageArrived(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    assert(context == NULL);
    assert(topicLen == 0);
    log_debug("MQTT message arrived,topic=%s,content=%.*s", topicName, message->payload);
    //TODO:处理消息,将消息交给消息路由处理，根据处理结果返回0或1
    if(app_router_mqttToDev(message->payload, message->payloadlen) == 0)
    {
        MQTTClient_freeMessage(&message);
        MQTTClient_free(topicName);
        return 1;
    }
    else
    {
        return 0;
    }
    
}

static void app_mqtt_deliveryComplete(void *context, MQTTClient_deliveryToken dt)
{
    assert(context == NULL);
    log_debug("MQTT delivery complete:token=%d", dt);
}